package com.fan.game;
import com.fan.tank.EnemyTank;
import com.fan.tank.MyTank;
import com.fan.tank.Tank;
import com.fan.util.MyUtil;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import static com.fan.util.Constant.*;

/**
 * 游戏窗口类
 */

public class GameFrame extends Frame implements Runnable{
    //第一次用再加载
    private Image overImage = null;
/**
 * 对窗口进行初始化
 */
    //定义一张和屏幕大小一致的图片
        private BufferedImage bufImg = new BufferedImage(FRAME_WIDTH,FRAME_HEIGHT,BufferedImage.TYPE_4BYTE_ABGR);

    //游戏状态
    private static int gameState;
    //菜单指向
    private int menuIndex;
    //标题栏的高度
    public static int titleBarh;
    //定义一个坦克对象
    private Tank myTank;
    //敌人的坦克容器
    private List<Tank> enemies = new ArrayList<>();

    public GameFrame(){
        initFrame();
        initEvenListener();
        //启动线程
        new Thread(this).start();
    }
    public void initGame(){
        gameState = STATE_MENU;
    }

    /**
     * 属性初始化
     */
    private void initFrame(){
        //设置标题
        setTitle(GAME_TITLE);
        //设置窗口可见
        setVisible(true);
        //设置窗口大小
        setSize(FRAME_WIDTH,FRAME_HEIGHT);
        //设置窗口左上角的坐标
        setLocation(FRAME_X,FRAME_Y);
        //设置窗口大小不可改变
        setResizable(false);
        //求标题栏的高度
        titleBarh = getInsets().top;
    }



    /**
     * 初始化窗口事件监听
     */
    private void initEvenListener (){
        //注册监听事件
        //关闭窗口
        addWindowListener(new WindowAdapter() {
            //点击关闭按钮方法自动调用
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });


        //键盘监听事件
        addKeyListener(new KeyAdapter() {
            //键盘按下的时候被调用
            @Override
            public void keyPressed(KeyEvent e) {
                //获得被按下的键值
                int keyCode = e.getKeyCode();
                //不同的游戏状态给出不同的处理方法
                switch(gameState){
                    case STATE_MENU:
                        keyPressdeEventMenu(keyCode);
                        break;
                    case STATE_ABOUT:
                        keyPressdeEventAbout(keyCode);
                        break;
                    case STATE_HELP:
                        keyPressdeEventHelp(keyCode);
                        break;
                    case STATE_OVER:
                        keyPressdeEventOver(keyCode);
                        break;
                    case STATE_RUN:
                        keyPressdeEventRun(keyCode);
                        break;
                }
            }
            //按键松开的时候回调内容
            @Override
            public void keyReleased(KeyEvent e) {
                int keyCode = e.getKeyCode();
                //不同的游戏状态给出不同的处理方法
               if(gameState == STATE_RUN){
                   keyReleasedEventRun(keyCode);
               }

            }


        });


    }


    //按键松开的时候，游戏中处理的方法
    private void keyReleasedEventRun(int keyCode) {
        switch (keyCode){
            case KeyEvent.VK_UP:
            case KeyEvent.VK_W:
            case KeyEvent.VK_DOWN:
            case KeyEvent.VK_S:
            case KeyEvent.VK_LEFT:
            case KeyEvent.VK_A:
            case KeyEvent.VK_RIGHT:
            case KeyEvent.VK_D:
                myTank.setState(Tank.STATE_STAND);
                break;
        }

    }

    //游戏结束的按键处理 TODO
    private void keyPressdeEventOver(int keyCode) {
         if(keyCode == KeyEvent.VK_ESCAPE){
             System.exit(0);
         }else if(keyCode == KeyEvent.VK_ENTER){
             setGameState(STATE_MENU);

             //游戏的某些属性需要重置
         }
    }


    //重置游戏
    private void resetGame(){

    }


    //游戏运行中按键的处理
    private void keyPressdeEventRun(int keyCode) {

        switch (keyCode){
            case KeyEvent.VK_UP:
            case KeyEvent.VK_W:
                myTank.setDir(Tank.DIR_UP);
                myTank.setState(Tank.STATE_MOVE);
                break;

            case KeyEvent.VK_DOWN:
            case KeyEvent.VK_S:
                myTank.setDir(Tank.DIR_DOWN);
                myTank.setState(Tank.STATE_MOVE);
                break;

            case KeyEvent.VK_LEFT:
            case KeyEvent.VK_A:
                myTank.setDir(Tank.DIR_LEFT);
                myTank.setState(Tank.STATE_MOVE);
                break;

            case KeyEvent.VK_RIGHT:
            case KeyEvent.VK_D:
                myTank.setDir(Tank.DIR_RIGHT);
                myTank.setState(Tank.STATE_MOVE);
                break;
            case KeyEvent.VK_SPACE:
                myTank.fire();
                break;
        }

    }

    private void keyPressdeEventAbout(int keyCode) {

    }

    private void keyPressdeEventHelp(int keyCode) {

    }


    //菜单状态下按键的处理
    private void keyPressdeEventMenu(int keyCode) {
        switch (keyCode){
            case KeyEvent.VK_UP:
            case KeyEvent.VK_W:

                if(--menuIndex < 0) {
                    menuIndex = MENUS.length - 1;
                }
                break;
            case KeyEvent.VK_DOWN:
            case KeyEvent.VK_S:
                if(++menuIndex > MENUS.length-1)
                {
                    menuIndex = 0;
                }
                break;
            case KeyEvent.VK_ENTER:
                newGame();
                break;
            }
        }


    /**
     * 开始新游戏的方法
     */
    private void newGame(){
        gameState = STATE_RUN;
        //创建坦克对象，创建敌人坦克对象
        myTank = new MyTank(400,200,Tank.DIR_UP);
        //使用一个单独的线程用于生产敌人的坦克
        new Thread(){
            @Override
            public void run(){
                while (true){
                    if(enemies.size() < ENEMY_MAX_COUNT){
                        Tank enemy = EnemyTank.createEnemy();
                        enemies.add(enemy);
                    }
                    try {
                        Thread.sleep(ENEMY_BORN_INTERVAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            }.start();
        }




    /**
     * 负责显示说有绘制内容，该方法不可主动调用，必须调用repaint（）；去调用
     * @param g1
     */
    public void update(Graphics g1){
        //得到图片的画笔
        Graphics g = bufImg.getGraphics();
        g.setFont(font);
        switch(gameState){
            case STATE_MENU:
                drawMenu(g);
                break;
            case STATE_ABOUT:
                drawAbout(g);
                break;
            case STATE_HELP:
                drawHelp(g);
                break;
            case STATE_OVER:
                drawOver(g);
                break;
            case STATE_RUN:
                drawRun(g);
                break;
        }
        //再使用系统的画笔将图片绘制到窗口上
        g1.drawImage(bufImg,0,0,null);
    }

    private void drawRun(Graphics g) {
        //绘制背景颜色
        g.setColor(Color.BLACK);
        g.fillRect(0,0,FRAME_WIDTH,FRAME_HEIGHT);


        drawEnemies(g);

        myTank.draw(g);

        bulletCollideTank();

        drawExplodes(g);
    }

    //绘制所有的敌人坦克,如果死亡从容器中移除
    private void drawEnemies(Graphics g){
        for (int i = 0; i < enemies.size(); i++) {
            Tank enemy = enemies.get(i);
            if(enemy.isDie()){
                enemies.remove(i);
                i--;
                continue;
            }
            enemy.draw(g);
        }
    }


//绘制游戏结束
    private void drawOver(Graphics g) {
        if(overImage == null){
            overImage = MyUtil.createImage("res/over.jpg");
        }

        int imgW = overImage.getWidth(null);
        int imgH = overImage.getHeight(null);

        g.drawImage(overImage,FRAME_WIDTH-imgW>>1,FRAME_HEIGHT - imgH >> 1,null);


        //添加提示按键信息
        g.setColor(Color.white);
        g.drawString(OVER_STR0,30,FRAME_HEIGHT-30);
        g.drawString(OVER_STR1,FRAME_WIDTH-200,FRAME_HEIGHT-30);
    }

    private void drawHelp(Graphics g) {

    }

    private void drawAbout(Graphics g) {
    }


    /**
     * 绘制菜单状态的方法
     * @param g
     */
    public void drawMenu(Graphics g){
        //绘制背景颜色
        g.setColor(Color.BLACK);
        g.fillRect(0,0,FRAME_WIDTH,FRAME_HEIGHT);

        final int STR_WIDTH = 76;
        final int DIS = 50;//行间距
        int x = FRAME_WIDTH - STR_WIDTH >>1;
        int y = FRAME_HEIGHT / 3;
        g.setColor(Color.WHITE);
        for (int i = 0; i < MENUS.length; i++) {
            if(i == menuIndex){//选中的菜单项的颜色设置为红色
                g.setColor(Color.RED);
            }else{
                g.setColor(Color.WHITE);
            }
            g.drawString(MENUS[i],x,y + DIS * i );
        }

    }


    /**
     * 刷新
     */
    @Override
    public void run() {
        while (true){
            repaint();
            try {
                Thread.sleep(REPAINT_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //敌人的子弹打我
    //我的坦克子弹打别人

    private void bulletCollideTank(){
        //我打别人
        for (Tank enemy : enemies) {
            enemy.collideBullets(myTank.getBullets());
        }


        //别人打我
        for (Tank enemy : enemies) {
            myTank.collideBullets(enemy.getBullets());
        }
    }


    //所有坦克的爆炸效果
    private void drawExplodes(Graphics g){
        for(Tank enemy : enemies){
            enemy.drawExplode(g);
        }
        myTank.drawExplode(g);
    }

    //获得游戏状态和修改游戏状态
    public static void setGameState(int gameState) {
        GameFrame.gameState = gameState;
    }

    public static int getGameState() {
        return gameState;
    }
}
